<?php


	// * start the timer for the page parse time log
	define('PAGE_PARSE_START_TIME', microtime());

  	// * prüfen ob bereits installiert ist
	if (strlen(WEBWI_DB_HOST) < 1) {
		if (is_dir('setup')) {
			header('Location: setup/index.php');
    	}
  	}
	
	global $webwiDB, $webwiLogger, $webwiErrorHandler, $webwiSecurity, $sessHandler;
	
	// * Seperator
	// * TODO: Wird demnächst ersetzt
	defined('DS') or define('DS', DIRECTORY_SEPARATOR);
	defined('NEWLINE')or define('NEWLINE', "\n");
	
	// * setzen php_self in globalen Fokus
	$PHP_SELF = (((strlen(ini_get('cgi.fix_pathinfo')) > 0) && ((bool)ini_get('cgi.fix_pathinfo') == false)) || !isset($_SERVER['SCRIPT_NAME'])) ? basename($_SERVER['PHP_SELF']) : basename($_SERVER['SCRIPT_NAME']);
	
	// * weitere Dateien mit definitionen laden
	include_once WEBWI_ROOT_PATH . DS . 'system' . DS . 'defines.php';
	include_once WEBWI_ROOT_PATH . DS . 'system' . DS . 'version.php';
	
	// * den class loader einbinden
	require_once WEBWI_ROOT_PATH . DS . 'system' . DS . 'classes' . DS . 'webwi_loader.php';
	
	// * Sani funktionen einbinden
	require_once WEBWI_ROOT_PATH . DS . 'system' . DS . 'sanitizing.php';
	
	// * laden der zusätzlichen libs
	require_once WEBWI_ROOT_PATH . DS . 'system' . DS . 'libs' . DS .  'global.php';
	
	// * die HTML Klasse laden
	WebwiLoad::load('webwiHTML');
	$webwiHTML = new webwiHTML();
	
	// * Datenbank laden
	include_once WEBWI_ROOT_PATH . DS . 'system' . DS . 'classes' . DS . 'databasefactory.php';
	$GLOBALS['webwiDB'] =& WebwiDatabaseFactory::getDatabaseConnection();
	
	// * Fehlebehandlung starten (webwiLogger / errorHandling / LogFiles / DebugConsole)
	require_once WEBWI_ROOT_PATH . DS . 'system' . DS . 'classes' . DS . 'error_handler.php';
	$GLOBALS['errorHandler'] = new WebwiErrorHandler;
	$webwiConfig['Error_Handler']['display'] = true;
	
	// * security class laden
	require_once WEBWI_ROOT_PATH . DS . 'system' . DS . 'classes' . DS . 'security.php';
	
	// set the application parameters
  	$config_query = $GLOBALS['webwiDB']->query('select config_key as cfgKey, config_value as cfgValue from '.$GLOBALS['webwiDB']->prefix('config').'');
  		while ($webwiCData = $GLOBALS['webwiDB']->fetchArray($config_query)) {
    		foreach($webwiCData as $webwiConfig['cfgKey'] => $webwiConfig['cfgValue']){ 
     			$webwiConfig[$webwiCData['cfgKey']] = $webwiCData['cfgValue']; 
 			}	 
  		}

	// * Merge file and db configs.
	if (file_exists($file = WEBWI_ROOT_PATH . DS . 'webwi_data/config/webwiconfig.php')) {
		$fileConfigs = include $file;
		$webwiConfig = array_merge($webwiConfig, (array) $fileConfigs);
		unset($fileConfigs, $file);
	} else {
		trigger_error('File Path Error: ' . 'webwi_data/config/webwiconfig.php' . ' does not exist.');
	}

	// * sprach Defiitionen laden
	loadLanguage('global');
	loadLanguage('errors');
	
	// * security class laden
	require_once WEBWI_ROOT_PATH . DS . 'system' . DS . 'classes' . DS . 'auth.php';
	
	// * set the session name 
  	session_name('NetwebWISID');

	// * Authentifizierung und starten der Session
	session_start();

	if (isClientLoggedIn() == FALSE) // * Prüfen ob der Benutzer eine geschützte Seite betreten möchte ohne sich vorher angemeldet zu haben
	{
		if (!empty($return))  // * Die letzte Seite abfangen auf die der Benutzer zugreifen wollte
		{
			if ($return === TRUE) // * Verarbeitungsschutz
			{
				header( "Location: login.php" );
				die();
			}
			else
			{
				header( "Location: login.php?return=".urldecode($return));
				die();
			}
		}
	}


/**
 * SESSION check up (Test if the information stored in the globals $_SESSION are valid)
 */
if (isClientLoggedIn() == TRUE)
{
	$clientverify = $GLOBALS['webwiDB']->query("SELECT `username`, `firstname`, `lastname`, `token`, `lastip` FROM ".$GLOBALS['webwiDB']->prefix('client')." WHERE `clientid` = '".$_SESSION['clientid']."' && `status` = 'Active'" );
	###
	$clientverify = $GLOBALS['webwiDB']->fetchArray($clientverify);
	if (
			($clientverify['username'] != $_SESSION['clientusername']) ||
			($clientverify['firstname'] != $_SESSION['clientfirstname']) ||
			($clientverify['lastname'] != $_SESSION['clientlastname']) ||
			($clientverify['token'] != session_id()) ||
			($clientverify['lastip'] != $_SERVER['REMOTE_ADDR'])
		)
	{
		session_destroy();
		header( "Location: login.php" );
		die();
	}


	$GLOBALS['webwiDB']->query("UPDATE ".$GLOBALS['webwiDB']->prefix('client')." SET `lastactivity` = '".$_SERVER['REQUEST_TIME']."' WHERE `clientid` = '".$_SESSION['clientid']."'" );

}



	if($webwiConfig['site_service'] == true)
	{
		if (isClientLoggedIn() == TRUE)
		{
			logout();
			exit('<h1><b>503 Service Unavailable</b></h1>'); //If the maintenance mode is ON, we drop the user.
		}
	}
	
	echo "<pre>";
	print_r($GLOBALS['webwiDB']);
	echo "</pre>";
?>